package cn.itcast.web.aspect;

import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    @Autowired
    private SysLogService sysLogService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpSession session;

    /**
     * 环绕通知
     *  1、参数:ProceedingJoinPoint
     *  2、返回值：object
     */
    @Around(value="execution(* cn.itcast.web.controller.*.*.*(..))")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {
        //1、增强
        SysLog sysLog = new SysLog();
        Object obj = session.getAttribute("loginUser");
        if(obj != null) {
            User user = (User) obj;
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());
        }
        sysLog.setIp(request.getRemoteAddr());
        sysLog.setTime(new Date());

        //执行的方法名称
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        String methodName = method.getName();
        sysLog.setMethod(methodName);
        //中文说明注释
        if(method.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping mapping = method.getAnnotation(RequestMapping.class);
            String name = mapping.name();
            sysLog.setAction(name);
        }

        sysLogService.save(sysLog);
        //2、调用被代理对象的方法
        return pjp.proceed();
    }
}
